package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("DetectdepartmentRestController")
public class DetectdepartmentRestController extends CmiEmaController {

	/**
	 * Create a new Detectdepartment entity
	 * 
	 */
	@RequestMapping(value = "/newDetectdepartment", method = RequestMethod.POST)
	@ResponseBody
	public Object newDetectdepartment(@RequestBody Detectdepartment detectdepartment) {
		detectdepartmentService.saveDetectdepartment(detectdepartment);
		return JSONObject.parse(cmiPsonService
				.toJsonString(detectdepartmentDAO.findDetectdepartmentByPrimaryKey(detectdepartment.getId()), 2));
	}

	@RequestMapping(value = "/restNewDetectdepartment", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewDetectdepartment(@RequestBody String detectdepartmentJson) {
		Detectdepartment detectdepartment = new Gson().fromJson(detectdepartmentJson, Detectdepartment.class);
		appendReferences(detectdepartment);
		detectdepartmentService.saveDetectdepartment(detectdepartment);
		return JSONObject.parse(cmiPsonService
				.toJsonString(detectdepartmentDAO.findDetectdepartmentByPrimaryKey(detectdepartment.getId()), 2));
	}

	@RequestMapping(value = "/saveDetectdepartment", method = RequestMethod.PUT)
	@ResponseBody
	public Detectdepartment saveDetectdepartment(@RequestBody Detectdepartment detectdepartment) {
		detectdepartmentService.saveDetectdepartment(detectdepartment);
		return detectdepartmentDAO.findDetectdepartmentByPrimaryKey(detectdepartment.getId());
	}

	@RequestMapping(value = "/restSaveDetectdepartment", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveDetectdepartment(@RequestBody String detectdepartmentJson) {
		Detectdepartment detectdepartment = new Gson().fromJson(detectdepartmentJson, Detectdepartment.class);
		appendReferences(detectdepartment);
		CmiPsonService cmiPsonService = new CmiPsonService();
		detectdepartmentService.saveDetectdepartment(detectdepartment);
		return JSONObject.parse(cmiPsonService
				.toJsonString(detectdepartmentDAO.findDetectdepartmentByPrimaryKey(detectdepartment.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteDetectdepartment/{detectdepartmentId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteDetectdepartment(@PathVariable Integer detectdepartmentId) {
		Detectdepartment detectdepartment = detectdepartmentDAO.findDetectdepartmentByPrimaryKey(detectdepartmentId);
		detectdepartmentService.deleteDetectdepartment(detectdepartment);
	}

	@RequestMapping(value = "/restConfirmDeleteDetectdepartments")
	@ResponseBody
	public Object restConfirmDeleteDetectdepartments(@RequestBody Set<Integer> deleteDetectdepartmentsIds) {
		Set<Detectdepartment> deleteDetectdepartments = detectdepartmentDAO
				.findDetectdepartmentsByIds(deleteDetectdepartmentsIds);
		Set<Detectdepartment> referencedDetectdepartments = detectdepartmentService
				.loadReferenceDetectdepartments(deleteDetectdepartments);
		deleteDetectdepartments.removeAll(referencedDetectdepartments);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedDetectdepartments);
		jsonObject.put("deleteEntitys", deleteDetectdepartments);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteDetectdepartments")
	@ResponseBody
	public Object restDeleteDetectdepartments(@RequestBody Set<Detectdepartment> deleteDetectdepartments) {
		Iterator<Detectdepartment> iterator = deleteDetectdepartments.iterator();
		while (iterator.hasNext()) {
			Detectdepartment currentDetectdepartment = iterator.next();
			detectdepartmentService.deleteDetectdepartment(currentDetectdepartment);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listDetectdepartments");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadDetectdepartment/{detectdepartmentId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectdepartment(@PathVariable Integer detectdepartmentId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(detectdepartmentDAO.findDetectdepartmentByPrimaryKey(detectdepartmentId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectdepartmentAddress/{detectdepartmentId}/address", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectdepartmentAddress(@PathVariable Integer detectdepartmentId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				detectdepartmentDAO.findDetectdepartmentByPrimaryKey(detectdepartmentId).getAddress(), 2,
				cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadDetectdepartmentDetects/{detectdepartmentId}/detects/{relateddetectId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectdepartmentDetects(@PathVariable Integer detectdepartmentId,
			@PathVariable Integer relateddetectId, @RequestBody CmiPagination cmiPagination) {
		Detect detect = detectDAO.findDetectByPrimaryKey(relateddetectId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detect, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectdepartmentUsers/{detectdepartmentId}/users/{relateduserId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectdepartmentUsers(@PathVariable Integer detectdepartmentId,
			@PathVariable Integer relateduserId, @RequestBody CmiPagination cmiPagination) {
		User user = userDAO.findUserByPrimaryKey(relateduserId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(user, 2, cmiPagination));
	}

	public void appendReferences(Detectdepartment detectdepartment) {

		Address address = detectdepartment.getAddress();
		if (address != null)
			detectdepartment.setAddress(addressService.findAddressByPrimaryKey(address.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Detect> detectsForDetectdepartment = new HashSet<>();
		for (Detect detect_Detectdepartment : detectdepartment.getDetectsForDetectdepartment()) {
			detectsForDetectdepartment.add(detectService.findDetectByPrimaryKey(detect_Detectdepartment.getId()));
		}
		detectdepartment.setDetectsForDetectdepartment(detectsForDetectdepartment);

		// 引用表是纯联系表的情况
		Set<User> usersForDetectdepartment = new HashSet<>();
		for (User userForDetectdepartment : detectdepartment.getUsersForDetectdepartment()) {
			usersForDetectdepartment.add(userService.findUserByPrimaryKey(userForDetectdepartment.getId()));
		}
		detectdepartment.setUsersForDetectdepartment(usersForDetectdepartment);
	}

	@RequestMapping(value = "/restGetDetectdepartmentAddress/{detectdepartmentId}/address", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectdepartmentAddress(@PathVariable Integer detectdepartmentId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				detectdepartmentDAO.findDetectdepartmentByPrimaryKey(detectdepartmentId).getAddress(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restGetDetectdepartmentDetects/{detectdepartmentId}/detects", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectdepartmentDetects(@PathVariable Integer detectdepartmentId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(detectdepartmentDAO.findDetectdepartmentByPrimaryKey(detectdepartmentId)
						.getDetectsForDetectdepartment(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetDetectdepartmentUsers/{detectdepartmentId}/users", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectdepartmentUsers(@PathVariable Integer detectdepartmentId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				detectdepartmentDAO.findDetectdepartmentByPrimaryKey(detectdepartmentId).getUsersForDetectdepartment(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restListDetectdepartments", method = RequestMethod.GET)
	@ResponseBody
	public Object restListDetectdepartments() {
		return JSONObject.parse(cmiPsonService.toJsonString(detectdepartmentService.loadDetectdepartments(), 2));
	}

	@RequestMapping(value = "/restListDetectdepartmentsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListDetectdepartmentsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = detectdepartmentPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Detectdepartment> detectdepartments = detectdepartmentDAO.findAllDetectdepartments(startResult,
				cmiPagination.getPaginationSize());
		String detectdepartmentString = cmiPsonService.toPsonString(detectdepartments, 2, cmiPagination);

		return JSONObject.parse(detectdepartmentString);
	}

	@RequestMapping("/detectdepartmentSelectBox")
	@ResponseBody
	public JSONObject detectdepartmentSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Address":
				entitySet = addressService.loadAddresssByIdSet(searchValue);
				break;

			// 被引用键
			case "Detect":
				entitySet = detectService.loadDetectsByIdSet(searchValue);
				break;

			case "User":
				entitySet = userService.loadUsersByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Address":
				entitySet = addressDAO.findAllAddresss((pageNumber - 1) * paginationSize, paginationSize);
				count = addressService.countAddresss();
				break;

			// 被引用键
			case "Detect":
				entitySet = detectDAO.findAllDetects((pageNumber - 1) * paginationSize, paginationSize);
				count = detectService.countDetects();
				break;

			case "User":
				entitySet = userDAO.findAllUsers((pageNumber - 1) * paginationSize, paginationSize);
				count = userService.countUsers();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Address":
				entitySet = addressDAO.findAddressByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = addressService.countAddresssByName(queryword);
				break;

			// 被引用键
			case "Detect":
				entitySet = detectDAO.findDetectByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = detectService.countDetectsByName(queryword);
				break;

			case "User":
				entitySet = userDAO.findUserByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = userService.countUsersByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
